//
//  LBEffect2Filter.mm
//  OpenGLGame
//
//  Created by Nguyen Cong Huy on 11/21/12.
//  Copyright (c) 2012 UIT. All rights reserved.
//

#include <iostream>

#include "LBEffect2Filter.h"

char fShaderStrEffect2[] = ""
"precision highp float;  "
"varying highp vec2 vtexCoor; "
"uniform sampler2D texture; "
"varying vec4 vposition;"

"varying highp vec2 vtexCoor2;"
"uniform sampler2D texture2; "

"float safeColorF(float color){"
"    if(color > 1.0) color = 1.0;"
"    else if(color < 0.0) color = 0.0;"
"    return color;"
"}"

"vec4 safeColor(vec4 color){"
"    color.r = safeColorF(color.r);"
"    color.g = safeColorF(color.g);"
"    color.b = safeColorF(color.b);"
"    return color;"
"}"

// radial gradient color function
"vec4 radialGradientColor(vec4 centerColor, vec4 outerColor, vec2 myPosition, vec2 centerPosition){"
"    float distance = clamp(distance(myPosition, centerPosition), 0.0, 1.0);"
"    return mix(centerColor, outerColor, distance);"
"}"
// radial gradient color function

// hard light blend function
"vec4 hardLight(vec4 base, vec4 blend, float opacity){"
"   vec4 result =  base;"
"    if (blend.r > 0.5) result.r = 1.0 - (1.0-base.r) *(1.0-2.0*(blend.r-0.5));"
"    else result.r = base.r * (2.0*blend.r);"

"    if (blend.g > 0.5) result.g = 1.0 - (1.0-base.g) *(1.0-2.0*(blend.g-0.5));"
"    else result.g = base.g * (2.0*blend.g);"

"    if (blend.b > 0.5) result.b = 1.0 - (1.0-base.b) *(1.0-2.0*(blend.b-0.5));"
"    else result.b = base.b * (2.0*blend.b);"

"    result = mix(base, result, opacity);"
"    return result;"
"}"
// END hard light blend function

"void main() "
"{ "
"     vec4 textureColor = texture2D(texture, vtexCoor); "
"   lowp vec4 texture2Color = texture2D(texture2, vtexCoor2);"

"   textureColor = hardLight(textureColor, texture2Color, 0.7);"

//statuation
"   highp float statuation = 0.3; "
"    float avg = (textureColor.r + textureColor.g + textureColor.b)/3.0; "
"   textureColor.r = avg + statuation*(textureColor.r - avg); "
"   textureColor.g = avg + statuation*(textureColor.g - avg);"
"   textureColor.b = avg + statuation*(textureColor.b - avg);"

"textureColor = safeColor(textureColor);"

//tint effect
"vec4 maxColor = vec4(0.845, 0.845, 0.902, 1.0);"
"vec4 minColor = vec4(0.196, 0.137, 0.039, 1.0);"
"textureColor.r = (textureColor.r - minColor.r)*(1.0/(maxColor.r - minColor.r));"
"textureColor.g = (textureColor.g - minColor.g)*(1.0/(maxColor.g - minColor.g));"
"textureColor.b = (textureColor.b - minColor.b)*(1.0/(maxColor.b - minColor.b));"

"textureColor = safeColor(textureColor);"

"    gl_FragColor = textureColor; "
"} ";

LBEffect2Filter::LBEffect2Filter(){
    init(0, fShaderStrEffect2);
}